using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

namespace WorkFlow.Tools.UI
{
    [ExecuteAlways][RequireComponent(typeof(UIBehaviourDriver))]
    [AddComponentMenu("WorkFlow/UGUI/UIBehaviour/ChildrenConstraint")]
    public class ChildrenConstraint : MonoBehaviour , IUIBehaviourDriverElement
    {
        [SerializeField] int order;
        [SerializeField] RectTransform[] rectTransforms;
        [SerializeField] Vector2 sizePadding;

        bool IUIBehaviourDriverElement.ElementEnabled => enabled;
        int IUIBehaviourDriverElement.Order => order;
        void IUIBehaviourDriverElement.OnRectTransformDimensionsChange()
        {
            Apply();
        }

        void Apply()
        {
#if UNITY_EDITOR
            _isValidate = false;
#endif
            if(transform is RectTransform rectTransform)
            {
                if (rectTransforms == null || rectTransforms.Length == 0)
                {
                    return;
                }

                foreach (var item in rectTransforms)
                {
                    if (item != null)
                    {
                        item.sizeDelta = rectTransform.sizeDelta + sizePadding;
                        item.anchoredPosition = rectTransform.anchoredPosition;
                    }
                }
            }
        }
        
#if UNITY_EDITOR
        bool _isValidate;
        bool IUIBehaviourDriverElement.IsValidated => _isValidate;
        void OnValidate()
        {
            _isValidate = true;
        }
#endif
    }
}

